package net.xju.common.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

public class JdbcUtilsV1 {
    private static DataSource dataSource = null;
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
    private static final QueryRunner queryRunner = new QueryRunner();


    static {
        try {
            InputStream resourceAsStream = JdbcUtilsV1.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties properties = new Properties();
            properties.load(resourceAsStream);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConnection()  {
        try {
            // 首先从threadLocal获取
            Connection connection = threadLocal.get();
            if (connection == null) {
                // 从连接池获取
                connection = dataSource.getConnection();
                threadLocal.set(connection);
            }
            return connection;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void close() {
        try {
            // 先从threadLocal获取
            Connection connection = threadLocal.get();
            if (connection != null) {
                threadLocal.remove();
                connection.setAutoCommit(true);
                connection.close();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 执行查询并返回对象列表
     */
    public static <T> List<T> executeQuery(Connection conn, Class<T> type, String sql, Object... params) {
        try {
            return queryRunner.query(conn, sql, new BeanListHandler<>(type), params);
        } catch (SQLException e) {
            throw new RuntimeException("Query failed", e);
        } finally {
            JdbcUtilsV1.close();
        }
    }

    /**
     * 执行查询并返回单个对象
     */
    public static <T> T executeQueryOne(Connection conn, Class<T> type, String sql, Object... params) {
        try {
            return queryRunner.query(conn, sql, new BeanHandler<>(type), params);
        } catch (SQLException e) {
            throw new RuntimeException("Query failed", e);
        } finally {
            JdbcUtilsV1.close();
        }
    }

    /**
     * 执行查询并返回单个值
     */
    public static <T> T executeQueryOneValue(Connection conn, String sql, Object... params) {
        try {
            return queryRunner.query(conn, sql, new ScalarHandler<>(), params);
        } catch (SQLException e) {
            throw new RuntimeException("Query failed", e);
        } finally {
            JdbcUtilsV1.close();
        }
    }

    /**
     * 执行更新操作（INSERT/UPDATE/DELETE）
     */
    public static int executeUpdate(Connection conn, String sql, Object... params) {
        try {
            return queryRunner.update(conn, sql, params);
        } catch (SQLException e) {
            throw new RuntimeException("Update failed", e);
        } finally {
            JdbcUtilsV1.close();
        }
    }

    /**
     * 带连接管理的查询方法
     */
    public static <T> List<T> executeQuery(Class<T> type, String sql, Object... params) {
        Connection conn = null;
        try {
            conn = JdbcUtilsV1.getConnection();
            return executeQuery(conn, type, sql, params);
        } finally {
            JdbcUtilsV1.close();
        }
    }

    /**
     * 带连接管理的单值查询方法
     */
    public static <T> T executeQueryOneValue(String sql, Object... params) {
        Connection conn = null;
        try {
            conn = JdbcUtilsV1.getConnection();
            return executeQueryOneValue(conn, sql, params);
        } finally {
            JdbcUtilsV1.close();
        }
    }

    /**
     * 带连接管理的更新方法
     */
    public static int executeUpdate(String sql, Object... params) {
        Connection conn = null;
        try {
            conn = JdbcUtilsV1.getConnection();
            return executeUpdate(conn, sql, params);
        } finally {
            JdbcUtilsV1.close();
        }
    }
    
    public static void main(String[] args) {
        new Thread(){
            @Override
            public void run() {
                System.out.println("ThreadA:"+JdbcUtilsV1.getConnection().hashCode());
                System.out.println("ThreadA:"+JdbcUtilsV1.getConnection().hashCode());
            }
        }.start();

        new Thread(){
            @Override
            public void run() {
                System.out.println("ThreadB:"+JdbcUtilsV1.getConnection().hashCode());
            }
        }.start();

    }
}
